cimsTech.service('sWSocket', ['$log', function($log) {
    // WebSocket的AngularJS service实现
    var self = this;
    var callbackhandler = [];
    // service 在angular中以new关键字创建,当服务被注入后,构造器实例化服务,创建唯一的socket连接
    var ws = new WebSocket('ws://' + window.location.host + window.location.pathname + 'Report');
    // 打开事件
    ws.onopen = function() {
        $log.info('\u94fe\u63a5\u5efa\u7acb\u6210\u529f');
    };
    // 关闭事件
    ws.onclose = function() {
        $log.info('\u94fe\u63a5\u5173\u95ed\u6210\u529f');
        alert('\u5df2\u4e0e\u670d\u52a1\u5668\u65ad\u5f00\u8fde\u63a5\u3002\u8bf7\u5237\u65b0\u91cd\u8bd5\uff01');
        window.location.reload();
    };
    // 收到消息
    ws.onmessage = function(event) {
        onMessage(event);
    };
    // 异常事件
    ws.onerror = function() {
        $log.warn('\u94fe\u63a5\u53d1\u751f\u5f02\u5e38');
        alert('\u94fe\u63a5\u53d1\u751f\u5f02\u5e38\u3002\u8bf7\u5237\u65b0\u91cd\u8bd5\uff01\u591a\u6b21\u65e0\u6548\u8bf7\u4e0e\u7cfb\u7edf\u7ba1\u7406\u5458\u8054\u7cfb');
        window.location.reload();
    };
    // 添加 WebSocket收到消息的回调方法
    self.addCallback = function(event, callback) {
        callbackhandler[event] = callback;
        return self;
    };
    // 收到消息后处理方法
    var onMessage = function(message) {
        var data = JSON.parse(message.data);
        // var ip = data.ip;
        switch(data.type) {
        case 'update' :
            // 报告开关状态更改
            callbackhandler['updateStatus'](data);
            // 报告数据更新
            callbackhandler['update'](data);
            break;
        case 'event' :
            // 设备连接状态更改
            callbackhandler['event'](data);
            break;
        default :
        }
    };
}]).service('ConnList', ['$http', '$localStorage', 'ErrMsg', function($http, $localStorage, ErrMsg) {
    // 连接池管理服务
    var self = this;
    var ConnectPool = [];
    // 创建本地存储连接名称,如果存在,则继续使用,如果不存在,则赋值新的对象
    $localStorage.connPool = $localStorage.connPool || {};
    // 连接池内置方法
    ConnectPool.getConnByIp = function(ip) {
        for(var i = 0; i < this.length; i++) {
            if(this[i].ip == ip) {
                return this[i];
            }
        }
    };
    ConnectPool.remove = function(conn) {
        var i = this.indexOf(conn);
        this.splice(i, 1);
    };
    // 服务被实例化时首先从服务器取回连接池内连接
    $http.get('rest/getConnList').success(function(response) {
        if(response.iecResponseMessage == 'SUCCESS') {
            if(response.connList instanceof Array && response.connList.length > 0) {
                angular.forEach(response.connList, function(conn) {
                    ConnectPool.push({
                        ip: conn.IP,
                        isConnect: conn.isConnect,
                        reportStatus: false,
                        displayName: $localStorage.connPool[conn.IP]
                    });
                });
            } else {
                ConnectPool.push({
                    ip: '',
                    isConnect: 'disconnect',
                    reportStatus: false,
                    displayName: ''
                });
            }
        } else {
            ErrMsg.show(response.iecResponseCause);
        }
    }).error(function(r, s) {
        ErrMsg.show('\u670d\u52a1\u5668\u9519\u8bef,\u9519\u8bef\u4ee3\u7801:' + s);
    });
    // 获取连接池信息接口
    self.getConnectList = function() {
        return ConnectPool;
    };
    // 向连接池内添加连接接口
    self.addConnect = function() {
        ConnectPool.push({
            ip: '',
            isConnect: 'disconnect',
            reportStatus: false,
            displayName: ''
        });
    };
    // 删除连接接口
    self.removeConn = function(conn) {
        ConnectPool.remove(conn);
    };
}]).factory('ConnectService', ['$http', '$uibModal', 'ConnList', 'ErrMsg', '$q', function($http, $uibModal, ConnList, ErrMsg, $q) {
    // 设备连接服务
    // 工厂模式的服务是调用方法的形式,调用了工厂模式的服务时将会执行上面的方法,这里方法返回了一个对象.
    return {
        connect: function(data) {
            // 创建promise服务对象
            var defer = $q.defer();
            var copy = data;
            $http.post('rest/Connect', {
                url: data.ip
            }, {
                cache: false
            }).success(function(resp) {
                if(resp.iecResponseMessage === 'ERROR') {
                    ConnList.getConnectList().getConnByIp(copy.ip).isConnect = 'disconnect';
                    ErrMsg.show(resp.iecResponseCause);
                    defer.reject();
                } else {
                    defer.resolve();
                }
            }).error(function(r, s) {
                ConnList.getConnectList().getConnByIp(copy.ip).isConnect = 'disconnect';
                ErrMsg.show('\u670d\u52a1\u5668\u9519\u8bef,\u9519\u8bef\u4ee3\u7801:' + s);
                defer.reject();
            });
            // 返回promise对象用于异步执行返回后的后续处理
            return defer.promise;
        },
        tearingConn: function(data) {
            var defer = $q.defer();
            $http.post('rest/tearingConn', data, {
                cache: false
            }).success(function(resp) {
                if(resp.iecResponseMessage === 'ERROR') {
                    ErrMsg.show(resp.iecResponseCause);
                    defer.reject(resp.ip);
                } else {
                    defer.resolve();
                }
            }).error(function(r, s) {
                ErrMsg.show('\u670d\u52a1\u5668\u9519\u8bef,\u9519\u8bef\u4ee3\u7801:' + s);
                defer.reject(r.ip);
            });
            return defer.promise;
        },
        removeConn: function(conn) {
            $http.delete('rest/Connect/' + conn.ip);
        }
    };
}]).service('SCADA', ['$http', 'ErrMsg', function($http, ErrMsg) {
    // 量测值读物服务
    var self = this, valueList = [];
    self.getValueList = function() {
        return valueList;
    };
    self.asyncValueList = function(data) {
        valueList.length = 0;
        $http.post('rest/Value', data, {
            cache: false
        }).success(function(resp) {
            if(resp.iecResponseMessage === 'ERROR') {
                ErrMsg.show(resp.iecResponseCause);
            } else {
                if(resp.values instanceof Array && resp.values.length > 0) {
                    angular.forEach(resp.values, function(value) {
                        if(typeof value === 'object') {
                            valueList.push(value);
                        }
                    });
                }
            }
        }).error(function(r, s) {
            ErrMsg.show('\u670d\u52a1\u5668\u9519\u8bef,\u9519\u8bef\u4ee3\u7801:' + s);
        });
    };
    self.clear = function() {
        valueList.length = 0;
    };
}]).service('ReportService', ['$http', '$q', 'sWSocket', 'ErrMsg', function($http, $q, sWSocket, ErrMsg) {
    // 报告开关服务
    this.switchReport = function(data) {
        var defer = $q.defer();
        $http.post('rest/Report', data).success(function(resp) {
            if(resp.iecResponseMessage === 'ERROR') {
                ErrMsg.show(resp.iecResponseCause);
                defer.reject();
            } else {
                defer.resolve();
            }
        }).error(function(r, s) {
            ErrMsg.show('\u670d\u52a1\u5668\u9519\u8bef,\u9519\u8bef\u4ee3\u7801:' + s);
            defer.reject();
        });
        return defer.promise;
    };
}]).service('ErrMsg', ['$uibModal', function($uibModal) {
    // 错误信息modal弹出服务
    this.show = function(message) {
        $uibModal.open({
            animation: true,
            templateUrl: 'ErrorMessage.html',
            controller: 'ModalInstanceCtrl',
            size: 'lg',
            resolve: {
                errorMsg: function() {
                    return message;
                }
            }
        });
    };
}]).service('fileService', ['$http', '$q', 'ErrMsg', function($http, $q, ErrMsg) {
    // 文件列表服务
    var fileList = [];
    this.getFileList = function() {
        return fileList;
    };
    this.readDir = function(item, ip) {
        var defer = $q.defer();
        $http.get('rest/getFileDir?url=' + ip + '&id=' + item.id).success(function(resp) {
            if(resp.iecResponseMessage === 'ERROR') {
                ErrMsg.show(resp.iecResponseCause);
                defer.reject();
            } else if(resp.nodes instanceof Array) {
                resp.nodes.sort(function(a, b) {
                    if(a.isParent === b.isParent) {
                        return a.title > b.title ? 1 : -1;
                    } else {
                        return b.isParent ? 1 : -1;
                    }
                });
                var data = [];
                angular.forEach(resp.nodes, function(node) {
                    if(node.isParent) {
                        node.icon = 'fa-folder';
                    } else {
                        node.icon = 'fa-file-text';
                    }
                    node.name = node.title.replace('\\', '');
                    data.push(node);
                });
                defer.resolve(data);
            } else {
                defer.reject();
            }
        }).error(function(r, s) {
            ErrMsg.show('\u670d\u52a1\u5668\u9519\u8bef,\u9519\u8bef\u4ee3\u7801:' + s);
            defer.reject();
        });
        return defer.promise;
    };
    this.removeFile = function(ip, files) {
        var defer = $q.defer();
        $http.post('rest/DeleteFile', {
            url: ip,
            items: JSON.stringify(files)
        }).success(function(resp) {
            if(resp.iecResponseMessage === 'ERROR') {
                ErrMsg.show(resp.iecResponseCause);
                defer.reject();
            } else {
                defer.resolve();
            }
        }).error(function(r, s) {
            ErrMsg.show('\u670d\u52a1\u5668\u9519\u8bef,\u9519\u8bef\u4ee3\u7801:' + s);
            defer.reject();
        });
        return defer.promise;
    };
    this.asyncFileList = function(data) {
        fileList.length = 0;
        angular.forEach(data, function(node) {
            if(node.isParent) {
                node.icon = 'fa-folder';
            } else {
                node.icon = 'fa-file-text';
            }
            node.name = node.title.replace('\\', '');
            fileList.push(node);
        });
    };
}]).factory('ProgressBar', ['$timeout', '$interval', function($timeout, $interval) {
    var ProgressBar = function() {
        this.max = 100;
        this.value = 1;
        this.isShow = false;
    };
    ProgressBar.prototype = {
        show: function() {
            var self = this;
            this.isShow = true;
            this.value = 10;
            $interval(function() {
                self.value++;
            }, 500, 40);
        },
        hide: function() {
            this.value = 100;
            this.isShow = false;
        }
    };
    return ProgressBar;
}]);